<?php
/**
 * Created by Shy
 * Date 2020/12/24
 * Time 16:31
 */


namespace app\admin\model;

use think\facade\Db;

class WxkCustomerFollow extends BasicModel
{
    public function __construct(array $data = [])
    {
        parent::__construct($data);
    }

    /**
     * 跟进记录列表
     * User: 万奇
     * Date: 2021/7/6 17:36
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function get_customer_follow_list($param){
        $where[]        = ['external_user_id', '=', $param['external_user_id']];
        $where[]        = ['follow_userid', '=', $param['follow_userid']];

        $list           = $this->where($where)->order(['create_at' => 'desc'])->paginate($param['limit'])->toArray();

        foreach ($list['data'] as &$v){
            $v['follow_user_name']      = get_operator_name($v['add_follow_user'], $v['user_type']);
            $v['photo']                 = $v['photo'] ? json_decode($v['photo']) : [];
        }

        return $list;
    }

    /**
     * 添加跟进记录
     * User: 万奇
     * Date: 2021/7/6 17:36
     * @param $param
     * @param $user_type
     * @throws \think\db\exception\DbException
     */
    public function add_customer_follow($param, $user_type){
        $insert                 = [
            'id'                => uuid(),
            'external_user_id'  => $param['external_user_id'],
            'follow_userid'     => $param['follow_userid'],
            'user_type'         => $user_type,
            'add_follow_user'   => $param['add_follow_user'],
            'follow_type'       => $param['follow_type'],
            'content'           => $param['content'],
        ];

        if (is_exists($param['photo'])){
            $insert['photo']    = json_encode($param['photo']);
        }

        $this->insert($insert);

        // 修改客户跟进状态
        Db::name('wxk_customer')->where(['external_user_id' => $param['external_user_id'], 'follow_userid' => $param['follow_userid']])->update(['follow_status' => $param['follow_type']]);

        // 添加客户互动轨迹
        $follow_count              = $this->where(['external_user_id' => $param['external_user_id']])->count();
        $follow_user_name          = get_operator_name($param['add_follow_user'], $user_type);

        $follow     = \StaticData::RESOURCE_NAME['follow_status'][$param['follow_type']];
        $content    = "$follow_user_name 第 $follow_count 次跟进，为 $follow 状态";
        WxkCustomerTrack::add_customer_track($param['external_user_id'], $content, 1);
    }

}